<template>
  <div class="p-2">
    <el-card shadow="never">
      <approvalButton
        @submitForm="submitForm"
        @approvalVerifyOpen="approvalVerifyOpen"
        @handleApprovalRecord="handleApprovalRecord"
        :buttonLoading="buttonLoading"
        :id="form.id"
        :status="form.status"
        :pageType="routeParams.type"
      />
    </el-card>
    <el-card shadow="never" style="height: 78vh; overflow-y: auto">
      <el-form ref="projectinfoFormRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="项目名称" prop="projectName">
          <el-input v-model="form.projectName" placeholder="请输入项目名称" />
        </el-form-item>
        <el-form-item label="建设地点" prop="constructionLocation">
          <el-input v-model="form.constructionLocation" placeholder="请输入建设地点" />
        </el-form-item>
        <el-form-item label="业主单位" prop="ownerUnit">
          <el-input v-model="form.ownerUnit" placeholder="请输入业主单位" />
        </el-form-item>
        <el-form-item label="合同金额" prop="contractAmount">
          <el-input v-model="form.contractAmount" placeholder="请输入合同金额" />
        </el-form-item>
        <el-form-item label="签署时间" prop="signingDate">
          <el-date-picker clearable
            v-model="form.signingDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择签署时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="客户邮箱" prop="customerEmail">
          <el-input v-model="form.customerEmail" placeholder="请输入客户邮箱" />
        </el-form-item>
         <el-form-item label="备注信息" prop="remarks">
            <el-input v-model="form.remarks" type="textarea" placeholder="请输入内容" />
        </el-form-item>

      </el-form>
    </el-card>
    <!-- 提交组件 111-->
    <submitVerify ref="submitVerifyRef" :task-variables="taskVariables" @submit-callback="submitCallback" />
    <!-- 审批记录 -->
    <approvalRecord ref="approvalRecordRef" />
    <el-dialog v-model="dialogVisible.visible" :title="dialogVisible.title" :before-close="handleClose" width="500">
      <el-select v-model="flowCode" placeholder="Select" style="width: 240px">
        <el-option v-for="item in flowCodeOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="submitFlow()"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="Projectinfo" lang="ts">
import { listProjectinfo, getProjectinfo, delProjectinfo, addProjectinfo, updateProjectinfo } from '@/api/project/projectinfo';
import { ProjectinfoVO, ProjectinfoQuery, ProjectinfoForm } from '@/api/project/projectinfo/types';


/**
 * AxiosResponse 和routeParams 是比较重要的参数
 */
import { startWorkFlow } from '@/api/workflow/task';
import SubmitVerify from '@/components/Process/submitVerify.vue';
import ApprovalRecord from '@/components/Process/approvalRecord.vue';
import ApprovalButton from '@/components/Process/approvalButton.vue';
import { AxiosResponse } from 'axios';
import { StartProcessBo } from '@/api/workflow/workflowCommon/types';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;


//路由参数
const routeParams = ref<Record<string, any>>({});
// 流程参数
const flowCode = ref<string>('');

const dialogVisible = reactive<DialogOption>({
  visible: false,
  title: '流程定义'
});
//提交组件
const submitVerifyRef = ref<InstanceType<typeof SubmitVerify>>();
//审批记录组件
const approvalRecordRef = ref<InstanceType<typeof ApprovalRecord>>();
//按钮组件
const approvalButtonRef = ref<InstanceType<typeof ApprovalButton>>();

const leaveFormRef = ref<ElFormInstance>();

const submitFormData = ref<StartProcessBo>({
  businessId: '',
  flowCode: '',
  variables: {}
});
const taskVariables = ref<Record<string, any>>({});


const buttonLoading = ref(false);

const projectinfoFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: ProjectinfoForm = {
  id: undefined,
  projectName: undefined,
  constructionLocation: undefined,
  ownerUnit: undefined,
  contractAmount: undefined,
  signingDate: undefined,
  customerEmail: undefined,
  projectStatus: undefined,
  projectManagerId: undefined,
  projectManagerName: undefined,
  remarks: undefined,
  refReason: undefined,
  approver: undefined,
  approvername: undefined,
  approveTime: undefined,
}
const data = reactive<PageData<ProjectinfoForm, ProjectinfoQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    projectName: undefined,
    constructionLocation: undefined,
    ownerUnit: undefined,
    contractAmount: undefined,
    signingDate: undefined,
    customerEmail: undefined,
    projectStatus: undefined,
    projectManagerId: undefined,
    projectManagerName: undefined,
    remarks: undefined,
    refReason: undefined,
    approver: undefined,
    approvername: undefined,
    approveTime: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "唯一标识不能为空", trigger: "blur" }
    ],
    projectName: [
      { required: true, message: "项目名称不能为空", trigger: "blur" }
    ],
  }
});


const handleClose = () => {
  dialogVisible.visible = false;
  flowCode.value = '';
  buttonLoading.value = false;
};
const { form, rules } = toRefs(data);

/** 表单重置 这些都是通用方法*/
const reset = () => {
  form.value = { ...initFormData };
  projectinfoFormRef.value?.resetFields();
};


/** 取消按钮 */
const cancel = () => {

  dialog.visible = false;
}


/** 提交按钮 */
/* const submitForm = () => {
  projectinfoFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateProjectinfo(form.value).finally(() =>  buttonLoading.value = false);
      } else {
         await addProjectinfo(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
  
    }
  });
} */

/** 提交按钮 */
const submitForm = (status: string) => {
  try {
    projectinfoFormRef.value?.validate(async (valid: boolean) => {
      if (valid) {
        buttonLoading.value = true;
        let res: AxiosResponse<ProjectinfoVO>;
        if (form.value.id) {
          res = await updateProjectinfo(form.value).finally(() =>  buttonLoading.value = false);
        } else {
          res = await addProjectinfo(form.value).finally(() =>  buttonLoading.value = false);
        }
        form.value = res.data;
        if (status === 'draft') {
          buttonLoading.value = false;
          proxy?.$modal.msgSuccess('暂存成功');
          proxy.$tab.closePage(proxy.$route);
          proxy.$router.go(-1);
        } else {
          if ((form.value.status === 'draft' && (flowCode.value === '' || flowCode.value === null)) || routeParams.value.type === 'add') {
            flowCode.value = flowCodeOptions[0].value;
            dialogVisible.visible = true;
            return;
          }
          //说明启动过先随意穿个参数
          if (flowCode.value === '' || flowCode.value === null) {
            flowCode.value = 'xx';
          }
          await handleStartWorkFlow(res.data);
        }
      }
    });
  } finally {
    buttonLoading.value = false;
  }
};

const submitFlow = async () => {
  handleStartWorkFlow(form.value);
  dialogVisible.visible = false;
};
//提交申请
const handleStartWorkFlow = async (data: ProjectinfoForm) => {
  try {
    submitFormData.value.flowCode = flowCode.value;
    submitFormData.value.businessId = data.id;
    //流程变量
    taskVariables.value = {
  /*     // leave2/6 使用的流程变量
      leaveDays: data.leaveDays,
      // leave4/5 使用的流程变量
      userList: ['1', '3', '4'] */
    };
    submitFormData.value.variables = taskVariables.value;
    const resp = await startWorkFlow(submitFormData.value);
    if (submitVerifyRef.value) {
      buttonLoading.value = false;
      submitVerifyRef.value.openDialog(resp.data.taskId);
    }
  } finally {
    buttonLoading.value = false;
  }
};
//审批记录
const handleApprovalRecord = () => {
  approvalRecordRef.value.init(form.value.id);
};
//提交回调
const submitCallback = async () => {
  await proxy.$tab.closePage(proxy.$route);
  proxy.$router.go(-1);
};
//审批
const approvalVerifyOpen = async () => {
  submitVerifyRef.value.openDialog(routeParams.value.taskId);
};

onMounted(() => {
  nextTick(async () => {
    routeParams.value = proxy.$route.query;
    reset();
    loading.value = false;
    if (routeParams.value.type === 'update' || routeParams.value.type === 'view' || routeParams.value.type === 'approval') {
      getInfo();
    }
  });
});
</script>
